package cn.bdqn.layui.controller;

import cn.bdqn.layui.entity.vo.DtoVo;
import cn.bdqn.layui.entity.Product;
import cn.bdqn.layui.entity.ProductType;
import cn.bdqn.layui.entity.Shop;
import cn.bdqn.layui.service.product.ProductDao;
import cn.bdqn.layui.service.product.ProductService;
import cn.bdqn.layui.service.productsuccess.ProductSuccessService;
import cn.bdqn.layui.service.shop.ShopService;
import cn.bdqn.layui.util.ResponseResult;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Controller
public class ProductController {

    @Resource
    ProductService productService;

    @Resource
    ProductDao productDao;

    @Resource
    ShopService shopService;

    @Resource
    ProductSuccessService productSuccessService;

    @Resource
    RestHighLevelClient restHighLevelClient;


    @RequestMapping("/shop/productlist")
    public String shopProductlist() {
        return "/views/product/product";
    }

    @RequestMapping("/productlist")
    @ResponseBody
    public String productlist(Integer page, Integer limit, String keyword) throws IOException {
        //查询库存
        List<Product> allProductByPage = productService.getAllProductByPage();
        //查询es哪个数据库
        SearchRequest searchRequest = new SearchRequest("product");
        //查询数据库所有数据
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //判断es和缓存数据是否相等
        if (allProductByPage.size() > searchResponse.getHits().getHits().length) {
            for (Product product : allProductByPage) {
                productDao.save(product);
            }
        }
        QueryBuilder queryBuilder = null;

        if (keyword != null) {
            //分词查询，采用默认分词器
            queryBuilder = QueryBuilders.matchQuery("productName", keyword);
        }
        //按照商品的价格排序
        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("productPrice").order(SortOrder.DESC);

        //设置分页
        page = page == null ? 1 : page;
        limit = limit == null ? 10 : limit;
        PageRequest pageRequest = PageRequest.of(page - 1, limit);

        //构建查询
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //查询条件
        builder.withQuery(queryBuilder);
        //构建排序
        builder.withPageable(pageRequest);
        builder.withSort(fieldSortBuilder);
        NativeSearchQuery nativeSearchQuery = builder.build();
        //执行方法
        Page<Product> products = productDao.search(nativeSearchQuery);
        //获取总条数
        int total = (int) products.getTotalElements();
        //获取查询到的数据内容
        List<Product> productList = products.getContent();
        JSONObject object = new JSONObject();
        object.put("data", productList);
        object.put("code", 0);
        object.put("msg", "");
        object.put("count", total);
        return object.toJSONString();

        /*SearchSourceBuilder builder = new SearchSourceBuilder();
        分词查询，采用默认分词器
        QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("productName", keyword);
        builder.query(matchQueryBuilder);
        builder.from(page - 1);
        builder.size(limit);
        searchRequest.source(builder);
        SearchResponse queryBuilder = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        List<Map<String, Object>> products = new ArrayList<>();
        for (SearchHit searchHit : queryBuilder.getHits().getHits()) {
            products.add(searchHit.getSourceAsMap());
        }*/
    }


    @RequestMapping("/toProduct")
    public String toProduct(Model model) {
        List<ProductType> productTypeList = productService.findProductType();
        List<Shop> shopList = shopService.findShopAll();
        model.addAttribute("productTypeList", productTypeList);
        model.addAttribute("shopList", shopList);
        return "/views/product/productform";
    }

    @RequestMapping("/addProduct")
    @ResponseBody
    public ResponseResult addProduct(Product product) {
        productService.addProduct(product);
        return new ResponseResult(200, "");
    }

    /**
     * 修改商品
     *
     * @param model
     * @return
     */
    @RequestMapping("/toupdateProduct")
    public String toupdateProduct(Model model) {
        List<ProductType> productTypeList = productService.findProductType();
        List<Shop> shopList = shopService.findShopAll();
        model.addAttribute("productTypeList", productTypeList);
        model.addAttribute("shopList", shopList);
        return "/views/product/productform";
    }


    @RequestMapping(value = "/miaosha", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ResponseResult miaoSha(@RequestBody @Validated DtoVo vo) {
        boolean b = productSuccessService.KillItem(vo.getProId(), vo.getUserId());
        if (b) {
            return new ResponseResult(0, "抢购成功", 0);
        }
        return new ResponseResult(0, "抢购失败", 0);
    }


}
